﻿using Grpc.Core;
using ImageDomain.Agg;
using ImageDomain.DE;
using ImageDomain.Services;
using Newtonsoft.Json;
using ScienceRpcServe.Protos;
using ScienceRpcServe.Utils;

namespace ScienceRpcServe.Services;

public class DicomSplitService : DicomSplit.DicomSplitBase
{
    private readonly ILogger<DicomSplitService> _logger;
    private readonly ISplitDicomsDE _splitDicomsDE;
    private readonly IArmBoneSegAgg _agg;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="agg"></param>
    public DicomSplitService(ILogger<DicomSplitService> logger, ISplitDicomsDE splitDicomsDe, IArmBoneSegAgg agg)
    {
        _logger = logger;
        _splitDicomsDE = splitDicomsDe;
        _agg = agg;
    }

    /// <summary>
    /// 主动设置 dicom序列路径
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<SplitResponse> SplitDicomsByDir(StringRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(SplitDicomsByDir)} | request: {JsonConvert.SerializeObject(request)}");

            await _splitDicomsDE.BuildSeriesDic(request.Value);

            return _splitDicomsDE.ToSplitResponse();
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(SplitDicomsByDir)} | {JsonConvert.SerializeObject(e)}");
            return new SplitResponse() { Remark = e.Message };
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<BoolResponse> ChooseSeries(StringRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(ChooseSeries)} | request: {JsonConvert.SerializeObject(request)}");

            _splitDicomsDE.SelectSeries(request.Value);

            await _agg.LoadOriginImage(_splitDicomsDE.CurrentSelectedSeries.Dicoms);

            return new BoolResponse() {IsSuccess = true};
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(ChooseSeries)} | {JsonConvert.SerializeObject(e)}");
            return new BoolResponse() { Remark = e.Message };
        }
    }

}
